package wyq.gy.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import java.util.Timer;
import java.util.TimerTask;

import wyq.gy.MainActivity;
import wyq.gy.lib.Constants;

/**
 * Created by Administrator on 2016/7/22.
 */
public class ServiceTwo extends Service {
    private Timer timer = new Timer();

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //if(!thread.isAlive()) {
         //   thread.start();
      //  new Thread(thread).start();//不这么写的话会报错 Thread第二次start会报错
       // }
 //       return START_REDELIVER_INTENT;


        if(! ServiceTwo.this.thread.isAlive()) {
            //  thread.start();


            new Thread(thread).start();
        }
        //  return START_REDELIVER_INTENT;



        if(!thread.isAlive()) {
            new Thread(thread).start();
        }
        return START_REDELIVER_INTENT;




    }

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            TimerTask task = new TimerTask() {

                @Override
                public void run() {
                    boolean b = MainActivity.isServiceWorked(ServiceTwo.this, Constants.PACKNAMEPOLLING+".ServiceOne");
                    boolean c=MainActivity.isServiceWorked(ServiceTwo.this,Constants.PACKNAMEPOLLING+".PollingService");
                    if (!b) {
                        Intent service = new Intent(ServiceTwo.this, ServiceOne.class);
                        startService(service);
                    }
                    if(!c){
                        PollingUtils.startPollingService(ServiceTwo.this, Constants.POLLINGTime, PollingService.class, PollingService.ACTION);

                    }
                }
            };
            timer.schedule(task, 0, 1000);
        }
    });

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }
}
